package com.mz361.stdapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mz361.common.enums.StatusEnum;
import com.mz361.common.utils.RedisUtil;
import com.mz361.common.utils.StringUtil;
import com.mz361.stdapi.domain.StandardDynamic;
import com.mz361.stdapi.repository.StandardDynamicRepository;
import com.mz361.stdapi.service.StandardDynamicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * @author niceale
 * @ date 2024/04/26
 */
@Service
public class StandardDynamicServiceImpl implements StandardDynamicService {

    @Autowired
    EntityManager entityManager;

    @Autowired
    private StandardDynamicRepository standardDynamicRepository;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据ID查询数据
     *
     * @param id 主键ID
     */
    @Override
    public StandardDynamic getById(Long id) {
        return standardDynamicRepository.findById(id).orElse(null);
    }

    /**
     * 获取分页列表数据
     *
     * @return 返回分页数据
     */

    @Override
    public Page<StandardDynamic> getPageList(String dynamicStatus, String keyword, Integer pageNo, Integer pageSize) {
        //处理默认值
        pageNo = pageNo == null ? 0 : pageNo;
        pageSize = pageSize == null ? 8 : pageSize;
        dynamicStatus = StringUtil.isEmpty(dynamicStatus) | "0".equals(dynamicStatus) ? null : dynamicStatus;
        String md5str = StringUtil.md5("md5:" + dynamicStatus + "," + keyword + "," + pageNo + "," + pageSize);
        PageRequest page = PageRequest.of(pageNo, pageSize, Sort.Direction.DESC, "publishDate");
        if (!redisUtil.exists("STANDARD:DYNAMIC:" + md5str)) {
            // 获取数据列表
            StandardDynamic standardDynamic = new StandardDynamic();
            standardDynamic.setDynamicStatus(dynamicStatus);
            // 创建分页对象
            ExampleMatcher matcher = ExampleMatcher.matching();
            if (StringUtil.notEmpty(keyword)) {
                standardDynamic.setTitle(keyword);
                matcher = ExampleMatcher.matching()
                        .withMatcher("title", ExampleMatcher.GenericPropertyMatcher::contains);

            }

            Example<StandardDynamic> example = Example.of(standardDynamic, matcher);
            Page<StandardDynamic> standardDynamicPage = standardDynamicRepository.findAll(example, page);
            redisUtil.setexValue("STANDARD:DYNAMIC:" + md5str, 300, JSONObject.toJSONString(standardDynamicPage));
            return standardDynamicPage;
        } else {
            return convertJsonStringToPage(redisUtil.getValue("STANDARD:DYNAMIC:" + md5str), page);
        }
    }

    @Override
    public List<StandardDynamic> getTop8StandardDynamic() {
        Query query = entityManager.createQuery("SELECT y FROM StandardDynamic y ORDER BY y.updateDate desc ", StandardDynamic.class);
        query.setMaxResults(8);
        return query.getResultList();
    }

    /**
     * 保存数据
     *
     * @param standardDynamic 实体对象
     */
    @Override
    public StandardDynamic save(StandardDynamic standardDynamic) {
        standardDynamic = standardDynamicRepository.save(standardDynamic);
        return standardDynamic;
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return standardDynamicRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    public static Page<StandardDynamic> convertJsonStringToPage(String jsonString, Pageable pageable) {
        // 解析JSON字符串为JSONObject
        JSONObject jsonObject = JSON.parseObject(jsonString);

        // 假设JSON对象中有一个名为"content"的字段，它是一个包含StandardPlan对象的数组
        JSONArray jsonArray = jsonObject.getJSONArray("content");
        Long totalElements = jsonObject.getLong("totalElements");

        // 创建StandardDynamic列表
        List<StandardDynamic> standardDynamics = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            // 将每个JSONObject转换为StandardPlan对象，这里需要自定义转换逻辑
            StandardDynamic standardDynamic = JSONObject.parseObject(jsonObj.toJSONString(), StandardDynamic.class);
            standardDynamics.add(standardDynamic);
        }

        // 创建Page对象
        return new PageImpl<>(standardDynamics, pageable, totalElements);
    }

}
